<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>聊天室</title>
  <link rel="stylesheet" href="./styles/reset.css">
  <link rel="stylesheet" href="./styles/styles.css">
</head>
<body>
    <div class="chart-box">
      <div class="chart-con">
        

        <div class="create-name">
          <input type="text" id="name" class="name" placeholder="请输入想创建的昵称">
          <div class="btn-group">
            <p id="setname" class="create create-btn">创建昵称</p>
            <p class="goback create-btn">退出聊天</p>
          </div>
        </div>

        <div class="send-msg" id="send-msg">
          <div class="bottom-con">
            <div class="emoji-box" id="emoji-box">
              <div class="emoji">
                <span class="s1">😀</span>
                <span class="s1">😁</span>
                <span class="s1">😂</span>
                <span class="s1">😃</span>
                <span class="s1">😅</span>
                <span class="s1">😄</span>
                <span class="s1">😆</span>
                <span class="s1">😉</span>
                <span class="s1">😊</span>
                <span class="s1">😎</span>
                <span class="s1">😍</span>
                <span class="s1">😘</span>
                <span class="s1">😗</span>
                <span class="s1">😚</span>
                <span class="s1">😐</span>
                <span class="s1">😏</span>
                <span class="s1">😣</span>
                <span class="s1">😥</span>
                <span class="s1">😶</span>
                <span class="s1">😑</span>
                <span class="s1">😫</span>
                <span class="s1">😯</span>
                <span class="s1">😒</span>
                <span class="s1">😝</span>
                <span class="s1">😜</span>
                <span class="s1">😌</span>
                <span class="s1">😤</span>
                <span class="s1">😷</span>
                <span class="s1">😓</span>
                <span class="s1">😵</span>
                <span class="s1">😳</span>
                <span class="s1">😡</span>
                <span class="s1">😠</span>
                <span class="s1">😱</span>
                <span class="s1">😰</span>
                <span class="s1">😬</span>
                <span class="s1">😨</span>
                <span class="s1">😧</span>
                <span class="s1">😭</span>
                <span class="s1">🔪</span>
                <span class="s1">⚽</span>
                <span class="s1">⚡</span>
                <span class="s1">⭐</span>
                <span class="s1">🌝</span>
                <span class="s1">🌼</span>
                <span class="s1">👀</span>
                <span class="s1">👅</span>
                <span class="s1">💎</span>
                <span class="s1">❓</span>
                <span class="s1">🚩</span>
                <span class="s1">😈</span>
                <span class="s1">🚽</span>
                <span class="s1">🌜</span>
                <span class="s1">🚲</span>
                <span class="s1">✈</span>
                <span class="s1">🚀</span>
                <span class="s1">👿</span>
                <span class="s1">👊</span>
                <span class="s1">🔞</span>
                <span class="s1">💖</span>
                <span class="s1">🈲</span>
                <span class="s1">🙋</span>
                <span class="s1">🙏</span>
                <span class="s1">🍙</span>
                <span class="s1">🍺</span>
                <span class="s1">🍹</span>
                <span class="s1">㊙</span>
                <span class="s1">🎲</span>
                <span class="s1">🎮</span>
              </div>
            </div>
            <div class="tools-box">
              <span class="emoji choose" id="choose">选择表情</span>
            </div>
            <div class="msg-box">
              <textarea rows="3"  id="text" class="words" placeholder="请输入" ></textarea>
              <p id="btn" class="send hide">发送</p> 
            </div>
          </div>
        </div>
        <div id="container">

        </div>
      </div>
    </div>
    <p class="tips" id="tips">群聊请先创建自定义昵称</p>

    <script>
    window.onload=function(){
      let choose = document.getElementById('choose');
      let emojiBox = document.getElementById('emoji-box');
      choose.onclick=function(){
        if(choose.innerHTML==='选择表情'){
          emojiBox.classList.add('emoji-on');
          choose.innerHTML='退出选择'
        }else{
          emojiBox.classList.remove('emoji-on');
          choose.innerHTML='选择表情'
        }
      }

      let s1 = document.querySelectorAll('.s1');
      let textarea = document.getElementById('text');
      let currentValue = textarea.value;
      s1.forEach((current,index)=>{
        current.onclick=function(){
          console.log(current)
          console.log(current.innerHTML)
          var choosed = current.innerHTML;
          let newValue = currentValue +' '+choosed;
          textarea.value=current.innerHTML;
          emojiBox.classList.remove('emoji-on');
          choose.innerHTML='选择表情'
        }
      })



      let yourName = localStorage.getItem('yourName');
      document.getElementById('name').value=yourName;

      document.querySelector('.goback').onclick=function(){
        window.location.href='./index.html'
      }

      var ws=null;
        
      document.getElementById('setname').onclick = function() {
         var name = document.getElementById('name').value;
          if(name === ''){
            let nameNotice = new Notification('消息提示', {
              body: '请先创建昵称'
            })
          }
          document.getElementById('tips').classList.add('tips-off');
          document.getElementById('send-msg').classList.add('send-on');
          ws = new WebSocket('ws://121.5.124.135:8000');
          console.log('ws',ws);
           
          //在建立连接时会触发
          ws.onopen = function(){
            //向服务器发送消息
            ws.send(JSON.stringify({
                name:name,
                type:'setname'
            }));
          }

          document.getElementById('btn').onclick = send;
          document.getElementById('text').onkeyup = function(e) {
              if(e.keyCode !== 13) return;
              send();
          }
       
          //自动接收服务器返回的数据
          //e代表一个事件  
          ws.onmessage = function(e){   
              var con = document.getElementById('container');
            
              //insertBefore(要插入的内容，要插入的位置之前)
              console.log(e.data)
            con.insertBefore(createChatPanel(JSON.parse(e.data)),con.children[0]);
          }
          //将加入房间按钮设置不可用（只能加入一次）
          document.getElementById('setname').classList.add('hide');
      }

      function createChatPanel(data) {
        var name = data.name;
        var text = data.text;
        let currentName = localStorage.getItem('yourName');

        var div = document.createElement('div');
        var span1= document.createElement('p');
        var span2= document.createElement('p');
        name==currentName?span1.classList.add('me'):'';
        name==currentName?span2.classList.add('me'):'';

        span1.innerHTML = name+' '+new Date().format("yyyy-MM-dd hh:mm:ss");
        span2.innerHTML = text;

        span2.style.fontWeight = '900';

        div.appendChild(span1);
        div.appendChild(span2);
        if(name==currentName){
          //是我自己
        }else if(name=='Server'){
          let userNotice = new Notification(`加入通知`, {
            body: text
          })
        }else{
          let userNotice = new Notification(`${name}发来一条消息`, {
            body: text
          })
        }

        return div;
      }
      //发送消息
      function send() {
        var text=document.getElementById('text');
            if(text.value === '')return;
            ws.send(JSON.stringify({
              text:text.value,
              type:"chat"
        }));             
        text.value = '';
      }

      //Date的原型中扩展了format方法，使其可以方便的格式化日期格式输出。
      Date.prototype.format = function(fmt) { 
        var o = { 
            "M+" : this.getMonth()+1,                 //月份 
            "d+" : this.getDate(),                    //日 
            "h+" : this.getHours(),                   //小时 
            "m+" : this.getMinutes(),                 //分 
            "s+" : this.getSeconds(),                 //秒 
            "q+" : Math.floor((this.getMonth()+3)/3), //季度 
            "S"  : this.getMilliseconds()             //毫秒 
        }; 
        if(/(y+)/.test(fmt)) {
                fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt; 
      }   
    }

    </script>
</body>
</html>